package com.wondertek.poms.service.util;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;

/**
 * @author anyouz
 * @date 2019/11/21 11:05
 */
@Component
public class BeanPropertiesUtil {
    /**
     * when the bean property is java.lang.String and is blank ,set to null
     *
     * @param t
     */
    public <T> void setNullIfStringIsBlank(T t) {
        Field[] fields = t.getClass().getDeclaredFields();
        for (int i = 0; i < fields.length; i++) {
            Field f = fields[i];
            f.setAccessible(true);
            try {
                if (f.getType().getName().equals("java.lang.String")) {
                    Object value = f.get(t);
                    if (value != null) {
                        if (StringUtils.isBlank(value.toString())) {
                            f.set(t, null);
                        }
                    }
                }
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
    }

    public <T> void setBlankIfStringIsNull(T t) {
        Field[] fields = t.getClass().getDeclaredFields();
        for (int i = 0; i < fields.length; i++) {
            Field f = fields[i];
            f.setAccessible(true);
            try {
                if (f.getType().getName().equals("java.lang.String")) {
                    Object value = f.get(t);
                    if (value == null) {
                        f.set(t, "");
                    }
                }
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
    }
}
